/*
 * Copyright 2013-2015 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.shiro.controller;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.shiro.ShiroConstants;
import com.xdtech.shiro.dao.SessionDao;
import com.xdtech.web.model.ResultMessage;

/**
 * 
 * @author max.zheng
 * @create 2015-2-8下午5:10:39
 * @since 1.0
 * @see
 */
@Controller
@RequestMapping("/session.do")
public class SessionController {
	@Autowired
	private SessionDao sessionDao;

	@RequestMapping(params = "session")
	public ModelAndView skipSession(HttpServletRequest request) {
		return new ModelAndView("sys/session/sessions_ftl");
	}

	@RequestMapping(params = "loadSessions")
	@ResponseBody
	public Map<String, Object> loadSessions(HttpServletRequest request) {
		Collection<Session> sessions = sessionDao.getActiveSessions();
		Map<String, Object> results = new HashMap<String, Object>();
		results.put("total", sessions.size());
		results.put("rows", sessions);
		return results;
	}

	@RequestMapping(params = "forceLogout")
	@ResponseBody
	public ResultMessage forceLogout(String sessionId) {
		try {
			Session session = sessionDao.readSession(sessionId);
			if (session != null) {
				session.setAttribute(ShiroConstants.SESSION_FORCE_LOGOUT_KEY,
						Boolean.TRUE);
			}
			sessionDao.delete(session);
		} catch (Exception e) {/* ignore */
		}
//		redirectAttributes.addFlashAttribute("msg", "强制退出成功！");
		return new ResultMessage();
	}

}
